/*
 * @Author: fishroom
 * @Date: 2023-01-05 14:22:48
 * @LastEditTime: 2023-01-09 14:19:22
 * @FilePath: \koa\app\socketHandler\loginHandler.ts
 */
import { Server as ServerIo, Socket } from "socket.io";
import { verify, sign } from "../util/webToken";
import ChitchatUser from "./ChitchatUser";
import socketUserServer from "../server/socketServer/socketUserServer";
import ChitchatGroup from "./ChitchatGroup";
import socketGroupServer from "../server/socketServer/socketGroupServer";
export default (
  io: ServerIo,
  userChitchat: Map<string, ChitchatUser>,
  groupChitchat: Map<number, ChitchatGroup>
) => {
  const login = async function(this: Socket, data: any) {
    if (!data.token) {
      return;
    }
    let { admin, error } = verify(data.token);
    if (error) {
      return;
    }
    let socketUser: any = await socketUserServer.getUserById(Number(admin.user_id));
    socketUser = socketUser.dataValues;

    if (!socketUser) {
      await socketUserServer.addSocketUser(admin);
    }
    let user = new ChitchatUser(socketUser || admin);
    const token = sign({ socketId: this.id, ...user });

    userChitchat.set(token, { ...socketUser, token });
    this.emit("loginSuccess", { token, ...socketUser });
    const friend: Map<string, ChitchatUser> = new Map(
      Object.entries(JSON.parse(socketUser.friend || "{}"))
    );
    const group: Map<string, ChitchatGroup> = new Map(
      Object.entries(JSON.parse(socketUser.group || "{}"))
    );
    group.forEach((item, key) => {
      let roomName = item.group_id + item.groupname;
      this.join(roomName);
      console.log(user.username + "加入群聊：" + roomName);
    });
    friend.forEach((value, key) => {
      let targetId = value.user_id;
      let roomName =
        (user?.user_id || 0) > targetId
          ? user?.user_id + "" + targetId
          : targetId + "" + user?.user_id;
      this.join(roomName);
      console.log(user.username + "加入聊天室:" + roomName);
    });
    this.join("public");
  };
  return {
    login,
  };
};
